package com.unitd.frame.springweb.plugins.velocity.directive;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;

import java.io.IOException;
import java.io.Writer;

/**
 * @desc 自定义一个Velocity的指令类, 实现一个阻塞指令管理类
 * @filename BlockDirective.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/4/2
 */
public class BlockDirective extends Directive {

	public BlockDirective() {
	}

	/**
	 * @desc 获取指令名称,这里定义的名称默认为block, 需要与velocity页面里的#block 对应
	 * @return
	 */
	@Override
	public String getName() {
		return "block";
	}

	@Override
	public int getType() {
		return 1;
	}

	@Override
	public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
		String name = DirectiveUtil.getRequiredArgument(context, node, 0, this.getName());
		OverrideDirective.OverrideNodeWrapper overrideNode = this.getOverrideNode(context, name);
		Node topNode = node.jjtGetChild(1);
		if (overrideNode == null) {
			return topNode.render(context, writer);
		} else {
			DirectiveUtil.setParentForTop(new OverrideDirective.OverrideNodeWrapper(topNode), overrideNode);
			return overrideNode.render(context, writer);
		}
	}

	private OverrideDirective.OverrideNodeWrapper getOverrideNode(InternalContextAdapter context, String name) {
		return (OverrideDirective.OverrideNodeWrapper) context.get(DirectiveUtil.getOverrideVariableName(name));
	}
}